﻿using LitJson;
using ServerSocket.common;
using ServerSocket.server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ServerSocket.controller
{
    class ControllerManager
    {

        private Dictionary<string, BaseController> dicController = new Dictionary<string, BaseController>();
        private Server server;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="server"></param>
        public ControllerManager(Server server)
        {
            this.server = server;
            InitController();
        }

        /// <summary>
        /// 初始化控制器
        /// </summary>
        private void InitController()
        {
            UserController user = new UserController();
            dicController.Add(user.RequestCode, user);
        }

        /// <summary>
        /// 处理客户端请求
        /// </summary>
        /// <param name="data"></param>
        /// <param name="client"></param>
        public void HandleRequest(string data, Client client)
        {
            string[] strArr = data.Split('|');
            string requestCode = strArr[0];
            string actionCode = strArr[1];
            string handlerData = strArr[2];
            BaseController controller;
            bool dic = dicController.TryGetValue(requestCode, out controller);
            if (!dic)
            {
                Console.WriteLine("[" + requestCode + "]处理器未找到");
                return;
            }
            MethodInfo mi = controller.GetType().GetMethod(actionCode);
            if (mi == null)
            {
                Console.WriteLine("[" + controller.GetType().Name + "]中没有对应的处理方法:[" + actionCode + "]");
                return;
            }
            object[] parameters = new object[] { handlerData, client, server };
            object o = mi.Invoke(controller, parameters);
            if (o == null || string.IsNullOrEmpty(o as string))
            {
                return;
            }
            server.SendResponse(client, actionCode, o as string);
        }

    }
}
